const fs = require('fs').promises;
const path = require('path');
const GRT_1 = require('./generate-vue-template_assets.js'); // 资产项目
const GRT_2 = require('./generate-vue-template.js');  // opro_web那边的项目

async function invokeGRTdown(frontObj, type = '1') {
    if (type == '1') {
        return useTheTemplate1(frontObj)
    } else {
        return useTheTemplate2(frontObj)
    }
}

async function useTheTemplate1(frontObj) {
    const currentDir = __dirname;
    const parentDir = path.dirname(currentDir); // 上级一层地址
    const grandDir = path.dirname(parentDir); // 上级两层地址

    const jsonData = frontJSONToBackJson(frontObj);

    // 示例字段配置 'id', 'name', 'email', 'createdAt'
    const tableFields = jsonData.tableFields;
    const searchFields = tableFields.filter(field => field.canSearch);

    const apiPath = jsonData.apiPath;
    const modelName = jsonData.modelName;
    const modelLabel = jsonData.modelLabel;
    const addApi = jsonData.addApi;
    const editApi = jsonData.editApi;
    const listApi = jsonData.listApi;
    const detailApi = jsonData.detailApi;
    const exportApi = jsonData.exportApi;
    const delApi = jsonData.delApi;

    try {
        await GRT_1.generateIndex({
            modelLabel,
            fields: tableFields,
            searchFields,
            apiPath,
            exportApi,
            fileName: 'index',
            modelName,
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_1.generateColumn({
            fields: tableFields,
            searchFields,
            apiPath,
            fileName: 'column',
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_1.gAddEditTemplate({
            modelLabel,
            formFields: tableFields,
            addApi,
            editApi,
            fileName: `${toUpperCamelCase(modelName)}AddEdit`,
            outputDir: path.join(grandDir, `public/low-code/${modelName}`),
            config: jsonData
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_1.gDetailTemplate({
            formFields: tableFields,
            fileName: `${toUpperCamelCase(modelName)}Detail`,
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_1.gServiceTemplate({
            modelLabel,
            formFields: tableFields,
            listApi,
            detailApi,
            delApi,
            addApi,
            editApi,
            fileName: 'service',
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }


    return modelName;
}

async function useTheTemplate2(frontObj) {
    const currentDir = __dirname;
    const parentDir = path.dirname(currentDir); // 上级一层地址
    const grandDir = path.dirname(parentDir); // 上级两层地址

    const jsonData = frontJSONToBackJson(frontObj);

    // 示例字段配置 'id', 'name', 'email', 'createdAt'
    const tableFields = jsonData.tableFields;
    const searchFields = tableFields.filter(field => field.canSearch);

    const apiPath = jsonData.apiPath;
    const modelName = jsonData.modelName;
    const modelLabel = jsonData.modelLabel;
    const addApi = jsonData.addApi;
    const editApi = jsonData.editApi;
    const listApi = jsonData.listApi;
    const detailApi = jsonData.detailApi;
    const exportApi = jsonData.exportApi;
    const delApi = jsonData.delApi;

    try {
        await GRT_2.generateIndex({
            modelLabel,
            fields: tableFields,
            searchFields,
            apiPath,
            exportApi,
            fileName: 'index',
            modelName,
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_2.generateColumn({
            fields: tableFields,
            searchFields,
            apiPath,
            fileName: 'column',
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_2.gAddEditTemplate({
            modelLabel,
            formFields: tableFields,
            addApi,
            editApi,
            fileName: `${toUpperCamelCase(modelName)}AddEdit`,
            outputDir: path.join(grandDir, `public/low-code/${modelName}`),
            config: jsonData
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_2.gDetailTemplate({
            formFields: tableFields,
            fileName: `${toUpperCamelCase(modelName)}Detail`,
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }

    try {
        await GRT_2.gServiceTemplate({
            modelLabel,
            formFields: tableFields,
            listApi,
            detailApi,
            delApi,
            addApi,
            editApi,
            fileName: 'service',
            outputDir: path.join(grandDir, `public/low-code/${modelName}`)
        });
    } catch (err) {
        console.error('生成失败:', err);
    }


    return modelName;
}

/** 前端传入的json文件转为后端的json文件 */
function frontJSONToBackJson(jsonData) {
    const theTemplate = jsonData[0];
    const basicInfo = theTemplate.props;
    const fields = theTemplate.subWidgets;
    const fieldList = [];
    for (let index = 0; index < fields.length; index++) {
        const fieldInfo = fields[index].props;
        fieldList.push({
            "fieldName": fieldInfo.fieldName,
            "fieldLabel": fieldInfo.fieldLabel,
            "checked": fieldInfo.checked,
            "canSearch": fieldInfo.canSearch,
            "fieldType": fieldInfo.fieldType,
            "charLength": fieldInfo.charLength,
            "options": fieldInfo.options,
            "dictCode": fieldInfo.dictCode,
        })
    }
    const templateData = {
        "modelName": basicInfo.modelName,
        "modelLabel": basicInfo.modelLabel,
        "listApi": basicInfo.listApi,
        "detailApi": basicInfo.detailApi,
        "delApi": basicInfo.delApi,
        "addApi": basicInfo.addApi,
        "editApi": basicInfo.editApi,
        "apiPath": basicInfo.apiPath,
        "exportApi": basicInfo.exportApi,
        "templateType": basicInfo.templateType,
        tableFields: fieldList
    }
    return templateData;
}

function toUpperCamelCase(str) {
    return str.replace(/-([a-z])/g, function (match) {
        return match.toUpperCase();
    }).replace(/-/g, '').replace(/(^\w{1})/, s => s.toUpperCase());
}

module.exports = {
    invokeGRTdown
}